<template>
  <div class="edit">
    <van-form @submit="onSubmit" class="form">
      <van-cell-group inset>
        <van-field
          required
          v-model="state.orderData.receiverName"
          name="receiverName"
          label="收货人"
          placeholder="请填写收货人"
          :rules="[{ required: true, message: '请填写收货人' }]"
        />
        <van-field
          required
          v-model="state.orderData.receiverPhone"
          name="receiverPhone"
          label="手机号码"
          placeholder="请填写手机号码"
          :rules="[{ required: true, message: '请填写手机号码' },
                    { validator: isMobile, message: '请填写正确的手机号码' }]"
        />
        <van-field
          v-model="state.orderData.receiverAddress"
          required
          readonly
          name="receiverAddress"
          label="所在地址"
          placeholder="请选择定位"
          :rules="[{ required: true, message: '请选择定位' }]"
          @click="onSelectAddress"
        >
          <template #input>
            <div>
              {{ state.orderData.receiverAddress }}
            </div>
          </template>
          <template #right-icon>
            <span class="address-right">
              <van-icon class="address-icon" name="location" />
              定位
            </span>
          </template>
        </van-field>
        <!-- <van-field
          type="textarea"
          rows="1"
          autosize
          v-model="state.orderData.receiverAddress"
          name="receiverAddress"
          placeholder="请填写详细地址"
          :rules="[{ required: true, message: '请填写详细地址' },
          {validator: validateAddress, message: '详细地址必须包含所在地区', trigger: 'onBlur'}]"
          @focus="onReceiverAddressFocus"
          @blur="onReceiverAddressBlur">
          <template #label>
            <div class="van-field__label--required">
              详细地址
            </div>
            <div class="fz-12">
              具体到楼层、门牌号
            </div>
          </template>
        </van-field> -->
        <van-field
          required
          readonly
          is-link
          label="收货时间"
          @click="onTime"
          :rules="[{ validator: validTime, message: '请选择收货时间' }]"
          >
          <template #input>
            <span v-if="state.orderData.startTime && state.orderData.endTime">
              {{getStartEndSpliceTime(state.orderData.startTime, state.orderData.endTime)}}
            </span>
            <span v-else class="c-c8c9cc">
              请选择收货时间
            </span>
          </template>
        </van-field>
      </van-cell-group>

      <template v-if="state.orderData.orderDtls && state.orderData.orderDtls.length">
        <van-cell-group class="mt-10" v-for="(item, index) in state.orderData.orderDtls" :key="index" inset>
          <div class="blessings">
            <div class="blessings-info">
              <van-image width="30" height="30" :src="item.mainPic"/>
              <span class="ml-10 fz-12 c-999">{{ item.name }}</span>
            </div>
            <van-field
              name="blessings"
              v-model="item.blessings"
              center
              type="textarea"
              rows="1"
              autosize
              :label="`祝福语`"
              maxlength="30"
              placeholder="请填写祝福语"
              :show-word-limit="!!(item.blessings && item.blessings.length === 30)"
            />
          </div>
        </van-cell-group>
      </template>
      
      <div class="footer">
        <van-button class="btn" round block color="#ff3102" native-type="submit" >
          确定修改
        </van-button>
      </div>
    </van-form>
    <timeSelector ref="timeSelectorRef" @confirm="onDateConfirm"></timeSelector>
    <contactTipDialog ref="contactTipDialogRef"></contactTipDialog>
  </div>
</template>

<script>
import { defineComponent, reactive, ref, onActivated, getCurrentInstance } from 'vue';
import { isMobile } from '@/utils/validate'
import timeSelector from './components/timeSelector'
import contactTipDialog from './components/contactTipDialog'
import { useRouter, useRoute } from 'vue-router'
import { orderDetail, updateOrder } from '@/api/common'
import {getStartEndSpliceTime} from '@/utils/time'
import { Toast } from 'vant';

export default defineComponent({
  name: 'OrderEdit',
  setup() {
    const instance = getCurrentInstance()
    const ctx = instance.proxy
    const timeSelectorRef = ref(null)
    const contactTipDialogRef = ref(null)
    const router = useRouter()
    const route = useRoute()
    const state = reactive({
      orderData: {},
      orderId: route.query.id,
      addressObj: {},
      isEditAddress: false
    })

    const onDateConfirm = ({date, time}) => {
      const times = time.split(' - ')
      state.orderData.startTime = `${date} ${times[0]}:00`
      state.orderData.endTime = `${date} ${times[1]}:00`
    }
    const onTime = () => {
      timeSelectorRef.value.show(state.orderData)
    }
    const getValidateMsg = () => {
      if (state.orderData.startTime) {
        const current = new Date()
        const start = new Date(state.orderData.startTime)
        if (start.getTime() <= current.getTime()) {
          return '所选时间应选择今日或之后的时间'
        }
      }
    }
    const onSubmit = () => {
      const errorMgs = getValidateMsg()
      if (errorMgs) {
        Toast.fail(errorMgs)
        return
      }
      updateOrder(state.orderData).then(res => {
        if (res.code === 200) {
          Toast.success(res.msg)
          setTimeout(() => {
            router.push({
              path: '/order/list'
            })
          }, 1000)
        } else {
          contactTipDialogRef.value.show(res.msg)
        }
      })
    }
    const onSelectAddress = () => {
      router.push({
        path: "/order/map",
        query: route.query,
      });
    };

    const handleSeleclAddress = (addressObj) => {
      state.addressObj = addressObj;
      state.isEditAddress = true
      if (state.addressObj) {
        state.orderData.receiverAddress = state.addressObj.cityname +
            ' ' +
            state.addressObj.name +
            state.addressObj.address + 
            state.addressObj.detailAddress;
        // state.orderData.receiverAddress = '';
        state.orderData.longitude = state.addressObj.location.lng;
        state.orderData.latitude = state.addressObj.location.lat;
        state.orderData.deptId = state.addressObj.deptId
      }
    };

    const validTime = () => {
      return !!(state.orderData.startTime && state.orderData.endTime)
    }

    const getOrderData = () => {
      orderDetail({id: state.orderId}).then(res => {
        state.orderData = res.data || {}
        // state.orderData['address'] = state.orderData['receiverAddress']
      })
    }

    const onReceiverAddressFocus = () => {
      if (!state.orderData.receiverAddress.includes(state.orderData.address)) {
        state.orderData.receiverAddress = state.orderData.address + state.orderData.receiverAddress 
      }
    }
    const onReceiverAddressBlur = () => {
      if (state.orderData.receiverAddress === state.orderData.address && state.isEditAddress) {
        state.orderData.receiverAddress = ''
      }
    }

    const validateAddress = (value, rule) => {
      if (state.orderData.receiverAddress.includes(state.orderData.address)) {
        return true
      } else {
        return false
      }
    }

    const init = () => {
      getOrderData()
    }
    init()

    const registerBusEvent = () => {
      ctx.$EventBus.on('selectAddress', handleSeleclAddress)
    }
    registerBusEvent()

    // 重入页面
    onActivated(() => {
      console.log(1)
      const from = route.query.from
      state.orderId = route.query.id
      if (from !== 'map') {
        state.isEditAddress = false
        getOrderData()
      }
    })

    return {
      state,
      isMobile,
      timeSelectorRef,
      onTime,
      onDateConfirm,
      onSubmit,
      onSelectAddress,
      validTime,
      getStartEndSpliceTime,
      contactTipDialogRef,
      onReceiverAddressFocus,
      onReceiverAddressBlur,
      validateAddress
    }
  },
  components: {
    timeSelector,
    contactTipDialog
  }
})
</script>

<style lang="less" scoped>
.edit {
  min-height: 100vh;
  background: #f6f8f7;
  .form {
    padding: 10px 0;
    .address-right {
      color: #1c75bc;
    }
    .address-icon {
      display: inline;
    }
  }
  .blessings {
    .blessings-info {
      display: flex;
      align-items: center;
      padding-left: var(--van-cell-vertical-padding);
      padding-top: var(--van-cell-vertical-padding);
    }
  }
  .footer {
    position: absolute;
    bottom: 10px;
    width: 100%;
    .btn {
      width: 94%;
      margin: 0 auto;
    }
  }
}
</style>
